package com.ljx.NoteBody.service.impl;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.ljx.NoteBody.common.MyException;
import com.ljx.NoteBody.dto.CommentsDto;
import com.ljx.NoteBody.entity.Comments;
import com.ljx.NoteBody.mapper.AgreeMapper;
import com.ljx.NoteBody.mapper.CommentsMapper;
import com.ljx.NoteBody.service.CommentsService;
import com.ljx.NoteBody.utils.TokenUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class CommentsServiceImpl implements CommentsService {

    @Autowired
    CommentsMapper commentsMapper;

    @Autowired
    AgreeMapper agreeMapper;

    @Override
    public void saveComment(Comments comments) {
        LocalDateTime time = LocalDateTime.now();
        comments.setCreateTime(time);
        comments.setUpdateTime(time);
        int i = commentsMapper.saveComment(comments);
        if(i <= 0) throw new MyException("保存评论错误");
    }

    @Override
    public List<CommentsDto> queryCommentByNoteId(Long noteId, HttpServletRequest request) {
        List<CommentsDto> data = new ArrayList<>();
        // 获取token中username
        String getToken =  request.getHeader("token");
        // 分别别判断处理
        if(getToken != null && !StringUtils.isEmpty(getToken)){
            // 判断token是否有效
            String username = "";
            try{
                DecodedJWT token = TokenUtil.verify(request.getHeader("token"));
                username = token.getClaim("username").asString();
            } catch (Exception e){
                throw new MyException("登陆失效，请推出后登录");
            }
            // 用来查找用户受否点赞
            int i = 0;
            for(Comments comment: commentsMapper.queryCommentByNoteId(noteId)){
                CommentsDto commentsDto = new CommentsDto();
                BeanUtils.copyProperties(comment, commentsDto);
                try{
                    i = agreeMapper.queryAgreeByUsernameAndCommentId(username, comment.getId());
                } catch (Exception e){
                    i = 0;
                }
                commentsDto.setAgree(i);
                data.add(commentsDto);
            }
        }
        else{
            for(Comments comment: commentsMapper.queryCommentByNoteId(noteId)){
                CommentsDto commentsDto = new CommentsDto();
                BeanUtils.copyProperties(comment, commentsDto);
                commentsDto.setAgree(0);
                data.add(commentsDto);
            }
        }
        return data;
    }
}
